package com.zhl.common.configuration;

import com.zhl.common.service.EmailService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;


/**
 * @description 邮件模板注册
 * @Author: z156940l@outlook.com
 * @className EmailServiceAutoConfiguration
 * @Date: 2024/7/20 23:16
 */
@Configuration
@EnableConfigurationProperties(EmailServiceProperties.class)
public class EmailServiceAutoConfiguration {

    @Bean
    public JavaMailSender javaMailSender(EmailServiceProperties emailServiceProperties) {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(emailServiceProperties.getHost());
        mailSender.setPort(emailServiceProperties.getPort());
        mailSender.setProtocol(emailServiceProperties.getProtocol());
        mailSender.setUsername(emailServiceProperties.getUsername());
        mailSender.setPassword(emailServiceProperties.getPassword());
        mailSender.setDefaultEncoding(emailServiceProperties.getDefaultEncoding());
        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.smtp.connectiontimeout", 5000);
        props.put("mail.smtp.timeout", 3000);
        props.put("mail.smtp.writetimeout", 5000);
        props.put("mail.smtp.auth", true);
        props.put("mail.smtp.starttls.enable", true);
        return mailSender;
    }

    @Bean
    @ConditionalOnMissingBean(EmailService.class)
    public EmailService emailService(JavaMailSender javaMailSender, EmailServiceProperties emailServiceProperties) {
        return new EmailService(javaMailSender, emailServiceProperties);
    }
}
